package com.toman.ui.msg;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itheima.pulltorefreshlib.PullToRefreshBase;
import com.itheima.pulltorefreshlib.PullToRefreshScrollView;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.squareup.picasso.Picasso;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.MessageDataBean;
import com.toman.R;
import com.toman.Util.ActionCallback;
import com.toman.Util.DefaultAcitonCallback;
import com.toman.Util.JsonUtils;
import com.toman.Util.TimeUtil;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.toolbar.ToolBarActivity;
import com.toman.ui.menu.MenuJump;
import com.toman.widget.CustomPopWindow;
import com.toman.widget.callback.StringLoadingCallback;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;

public class MsgUnReadActivity extends ToolBarActivity {

    @BindView(R.id.tv_select0)
    TextView tvSelect0;
    @BindView(R.id.iv_select0)
    ImageView ivSelect0;
    @BindView(R.id.rl_select0)
    RelativeLayout rlSelect0;
    @BindView(R.id.tv_select1)
    TextView tvSelect1;
    @BindView(R.id.iv_select1)
    ImageView ivSelect1;
    @BindView(R.id.rl_select1)
    RelativeLayout rlSelect1;
    @BindView(R.id.ll_base)
    LinearLayout llBase;
    @BindView(R.id.lv)
    RecyclerView lv;
    @BindView(R.id.mMangeNodata)
    TextView mMangeNodata;
    CommonAdapter<MessageDataBean> adapter;
    @BindView(R.id.mPullToRefreshScrollView)
    PullToRefreshScrollView mPullToRefreshScrollView;
    MenuItem menuItem;
    @BindView(R.id.view)
    View view;
    private List<MessageDataBean> list = new ArrayList<>();

    private List<MessageDataBean> listWorkUnread = new ArrayList<>();
    private List<MessageDataBean> listWorkRead = new ArrayList<>();
    private List<MessageDataBean> listMsgUnread = new ArrayList<>();
    private List<MessageDataBean> listMsgRead = new ArrayList<>();
    private CustomPopWindow mCustomPopWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_msg_unread);
        ButterKnife.bind(this);
        initView();
        initToolBar(  "未处理工作");

    }

    @Override
    protected void onResume() {
        super.onResume();
        get();
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.toolbar_clear, menu);
//        menuItem = menu.findItem(R.id.menu_clear);
//        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
//            @Override
//            public boolean onMenuItemClick(MenuItem item) {
//                switch (item.getItemId()) {
//                    case R.id.menu_clear:
//                        if (menuItem.getTitle().equals("清空已处理")) {
//                            List<MessageDataBean> dataBeans = new ArrayList<>();
//                            dataBeans.addAll(listWorkRead);
//                            if (dataBeans.size()<=0){
//                                ToastUtil.error(getApplicationContext(),"所有已处理工作已清空");
//                            }
//                            deleteDialog(MsgUnReadActivity.this, NewBaseUrl.getNotifyClear, dataBeans, token, "清空消息", new DefaultAcitonCallback() {
//                                @Override
//                                public void run() {
//                                    super.run();
//                                    get();
//                                }
//                            });
//                        } else if (menuItem.getTitle().equals("清空...")) {
//                            showPopMenu(view);
//                        }
//                        break;
//                }
//                return false;
//            }
//        });
//
//        return true;
//    }


    private void initView() {
        adapter = new CommonAdapter<MessageDataBean>(this, R.layout.item_msg_type, list) {
            @Override
            protected void convert(ViewHolder holder, MessageDataBean item, final int position) {
                holder.setText(R.id.tv_name, item.getName());
                holder.setText(R.id.tv_content, item.getMessageContent());
                holder.setText(R.id.tv_time, TimeUtil.getFormatTime(TimeUtil.convert2long(item.getMessageTime())));
                TextView tv_name = holder.getView(R.id.tv_name);
                TextView tv_content = holder.getView(R.id.tv_content);
                TextView tv_time = holder.getView(R.id.tv_time);
                if (item.getDealStatus() == 0) {
                    if (item.getReadStatus() == 0) {
                        tv_name.setTextColor(getResources().getColor(R.color.black33));
                        tv_content.setTextColor(getResources().getColor(R.color.black33));
                        tv_time.setTextColor(getResources().getColor(R.color.black33));
                    } else {
                        tv_name.setTextColor(getResources().getColor(R.color.black99));
                        tv_content.setTextColor(getResources().getColor(R.color.black99));
                        tv_time.setTextColor(getResources().getColor(R.color.black99));
                    }
                } else if (item.getDealStatus() == 1) {
                    tv_name.setTextColor(getResources().getColor(R.color.black33));
                    tv_content.setTextColor(getResources().getColor(R.color.black33));
                    tv_time.setTextColor(getResources().getColor(R.color.black33));
                } else {
                    tv_name.setTextColor(getResources().getColor(R.color.black99));
                    tv_content.setTextColor(getResources().getColor(R.color.black99));
                    tv_time.setTextColor(getResources().getColor(R.color.black99));
                }
                ImageView imageView = holder.getView(R.id.iv_icon);
                if (position + 1 == list.size()) {
                    holder.getView(R.id.line).setVisibility(View.GONE);
                }
                if (item.getUrl() != null) {
                    Picasso.with(getApplicationContext()).load(item.getUrl()).into(imageView);
                }
            }
        };
        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                List<MessageDataBean> beanlist = adapter.getDatas();
                MessageDataBean bean = beanlist.get(position);
                ToastUtil.print(bean.getType() + "：" + bean.getOperateType());
                if (bean.getDealStatus() == 0) {
                    List<MessageDataBean> dataBeans = new ArrayList<>();
                    dataBeans.add(bean);
                    bean.setClearType("4");
                    clickEvent(MsgUnReadActivity.this, NewBaseUrl.getNotifyClear, dataBeans, token, "", null);
                }
                MenuJump.dealMsg(MsgUnReadActivity.this, bean);
//                dealMsg(bean);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                List<MessageDataBean> beanlist = adapter.getDatas();
                MessageDataBean bean = beanlist.get(position);
                if (bean.getDealStatus() != 1) {
                    List<MessageDataBean> dataBeans = new ArrayList<>();
                    dataBeans.add(bean);
                    deleteDialog(MsgUnReadActivity.this, NewBaseUrl.getNotifyClear, dataBeans, token, "清除选中的消息", new DefaultAcitonCallback() {
                        @Override
                        public void run() {
                            super.run();
                            get();
                        }
                    });
                }
                return true;
            }
        });

        lv.setAdapter(adapter);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        lv.setLayoutManager(manager);
        mPullToRefreshScrollView.setMode(PullToRefreshBase.Mode.PULL_DOWN_TO_REFRESH);
        mPullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                dialog = null;
                dialogList.clear();
                get();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
//                customer(page, 2, etSearch.getText().toString().trim());

            }
        });


    }

    public void get() {
        OkHttpUtils
                .post(NewBaseUrl.getNotifyMessageByType)
                .headers("token", token)
                .execute(new StringLoadingCallback(this, mPullToRefreshScrollView) {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "消息类型详情: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");

                        ViewUtil.lagout(code, MsgUnReadActivity.this);
                        if (code == 0) {
                            list.clear();
                            listWorkUnread = new ArrayList<MessageDataBean>(JSONArray.parseArray(jsonObj.getString("toDoList"), MessageDataBean.class));
//                            listWorkRead = new ArrayList<MessageDataBean>(JSONArray.parseArray(jsonObj.getString("hadDoneList"), MessageDataBean.class));
//                            listMsgUnread = new ArrayList<MessageDataBean>(JSONArray.parseArray(jsonObj.getString("toReadList"), MessageDataBean.class));
//                            listMsgRead = new ArrayList<MessageDataBean>(JSONArray.parseArray(jsonObj.getString("hadReadList"), MessageDataBean.class));
                            if (status.equals("0")) {
                                list.addAll(listWorkUnread);
//                                list.addAll(listWorkRead);

                            }
//                            else if (status.equals("1")) {
//                                list.addAll(listMsgUnread);
//                                list.addAll(listMsgRead);
//                            }
//                            tvSelect0.setText("未处理工作(" + listWorkUnread.size() + ")");
//                            tvSelect1.setText("未读消息(" + listMsgUnread.size() + ")");
                            initToolBar("未处理工作(" + listWorkUnread.size() + ")");
                            adapter.notifyDataSetChanged();

                            try {
                                if (list.size() <= 0) {
                                    mMangeNodata.setVisibility(View.VISIBLE);
                                } else {
                                    mMangeNodata.setVisibility(View.GONE);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));

                        }
//                        if (bgaRefresh != null) {
//                            bgaRefresh.endRefreshing();
//                        }
                    }
                });
    }

    public static void deleteDialog(Activity context, String url, List<MessageDataBean> ids, String token, String title, ActionCallback actionCallback) {
        //LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化
        new AlertDialog.Builder(context)
                //对话框的标题
                .setTitle("确定要" + title + "？")
                //设定显示的View
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", (dialog, whichButton) -> {
                    clickEvent(context, url, ids, token, title, actionCallback);
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create().show();
    }

    private static void clickEvent(Activity context, String url, List<MessageDataBean> ids, String token, String title, ActionCallback actionCallback) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("messageDataList", ids);
        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(url)
                .headers("token", token)
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", title + ":" + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, context);


                        if (code == 0) {
                            if (actionCallback != null) {
                                actionCallback.run();
                                ToastUtil.success(context, jsonObj.getString("msg"));

                            }
                        } else {
                            ToastUtil.error(context, jsonObj.getString("msg"));
                        }
                    }
                });
    }

    private void setStatus(String status) {
        this.status = status;

        switch (status) {
            case "0":
                menuItem.setTitle("清空已处理");
                tvSelect0.setTextColor(getResources().getColor(R.color.button_blue));
                tvSelect1.setTextColor(getResources().getColor(R.color.black33));
                ivSelect0.setBackgroundColor(getResources().getColor(R.color.button_blue));
                ivSelect1.setBackgroundColor(getResources().getColor(R.color.white));
                get();

                break;
            case "1":
                menuItem.setTitle("清空...");
                tvSelect1.setTextColor(getResources().getColor(R.color.button_blue));
                tvSelect0.setTextColor(getResources().getColor(R.color.black33));
                ivSelect1.setBackgroundColor(getResources().getColor(R.color.button_blue));
                ivSelect0.setBackgroundColor(getResources().getColor(R.color.white));
                get();

                break;

        }
    }


    private void showPopMenu(View button) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_menu_msg_clear, null);
        //处理popWindow 显示内容
//        View view = contentView.findViewById(R.id.menu3);
//        ViewUtil.permission(getApplicationContext(), BaseEnum.DISPATCHING.has(PermEnum.DELETE), view);

        handleLogic(contentView);

        //创建并显示popWindow
        if (mCustomPopWindow == null) {

            mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(contentView)
                    .create()
                    .showAsDropDown(button, 0, 20);
//            mCustomPopWindow.getPopupWindow().setOnDismissListener(new PopupWindow.OnDismissListener() {
//                @Override
//                public void onDismiss() {
//                    WindowManager.LayoutParams lp = getWindow().getAttributes();
//                    lp.alpha = 1f;
//                    getWindow().setAttributes(lp);
//                }
//            });

        } else {

            mCustomPopWindow.showAsDropDown(button, 0, 20);
        }

    }

    private void handleLogic(View contentView) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (mCustomPopWindow != null) {
//                    mCustomPopWindow.dissmiss();
//                }
                switch (v.getId()) {
                    case R.id.tv_read:
                        mCustomPopWindow.dissmiss();
                        List<MessageDataBean> dataBeans = new ArrayList<>();
                        dataBeans.addAll(listMsgRead);
                        deleteDialog(MsgUnReadActivity.this, NewBaseUrl.getNotifyClear, dataBeans, token, "清空已读消息", new DefaultAcitonCallback() {
                            @Override
                            public void run() {
                                super.run();
                                get();

                            }
                        });
                        break;
                    case R.id.tv_all:
                        mCustomPopWindow.dissmiss();

                        dataBeans = new ArrayList<>();
                        dataBeans.addAll(listMsgRead);
                        dataBeans.addAll(listMsgUnread);
                        deleteDialog(MsgUnReadActivity.this, NewBaseUrl.getNotifyClear, dataBeans, token, "清空全部消息", new DefaultAcitonCallback() {
                            @Override
                            public void run() {
                                super.run();
                                get();
                            }
                        });
                        break;

                }

            }
        };
        contentView.findViewById(R.id.tv_read).setOnClickListener(listener);
        contentView.findViewById(R.id.tv_all).setOnClickListener(listener);

    }

    @OnClick({R.id.rl_select0, R.id.rl_select1})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_select0:
                setStatus("0");
                break;
            case R.id.rl_select1:
                setStatus("1");
                break;
        }
    }

}
